package com.nuaa.service.admin.impl;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.nuaa.dao.inter.CustomDaoInter;
import com.nuaa.domain.user.customer.CustomerInfo;
import com.nuaa.service.admin.inter.SystemServiceInter;
import com.nuaa.utils.DataGrid;
import com.nuaa.utils.PageInfo;

@Service("systemService")
public class SystemServiceImpl implements SystemServiceInter {

	@Resource
	private CustomDaoInter customDao;

	@Override
	public DataGrid<CustomerInfo> getAll(PageInfo pager, CustomerInfo critiriaCustom) throws Exception {
		String critiria = prepareCritiria(critiriaCustom);
		int[] fm = pager.getFirstindexAndMaxindex();
		DataGrid<CustomerInfo> dataGrid = new DataGrid<>();
		try {
			List<CustomerInfo> rows = customDao.getAllByPage(fm[0], fm[1], critiria);
			long totle = customDao.getCount(critiria);
			dataGrid.setTotal(totle);
			dataGrid.setRows(rows);

		} catch (Exception e) {
			throw new Exception("数据查询发生异常");
		}
		return dataGrid;
	}

	/**
	 * 生成条件字符串
	 * 
	 * @param critiriaCustom
	 * @return
	 */
	private String prepareCritiria(CustomerInfo critiriaCustom) {
		StringBuffer criSb = new StringBuffer(" where 1=1 ");
		Field[] fields = critiriaCustom.getClass().getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			String fieldName = fields[i].getName();
			String firstChar = fieldName.substring(0, 1).toUpperCase();
			String getter = "get" + firstChar + fieldName.substring(1, fieldName.length());
			Method method;
			try {
				method = critiriaCustom.getClass().getMethod(getter, new Class[] {});
				Object value = method.invoke(critiriaCustom, new Object[] {});
				if (value != null && !value.equals("")) {
					criSb.append("and " + fieldName + " like '%" + value + "%' ");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		return criSb.toString();
	}

}
